package cn.zzq.aix.nativeinterface.javareflector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Logcater extends Thread implements LogcatListener {
	private LogcatListener logcatListener = null;
	private boolean isListening = false;

	public void setLogcatListener(LogcatListener logcatListener) {
		this.logcatListener = logcatListener;
	}

	@Override
	public void logcat(String log) {
		if (logcatListener != null) {
			logcatListener.logcat(log);
		}
	}

	@Override
	public void run() {
		isListening = true;

		try {
			Runtime runtime = Runtime.getRuntime();
			runtime.exec("logcat -c").destroy();
			Process process = runtime.exec("logcat");
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			while (((line = reader.readLine()) != null)) {
				if (isInterrupted()) {
					reader.close();
					process.destroy();
					break;
				} else {
					logcat(line);
				}
			}
		} catch (IOException e) {
			throw new ReflectException(null, "Logcater.run<>", e);
		} finally {
			isListening = false;
		}

	}

	public void startLogcat() {
		this.start();
	}
	
	public void stopLogcat() {
		this.interrupt();
		while (isListening) {
			// 只要还在运行就卡在当前
		}
	}

}
